package top.infopub.mgr.sys.web;


import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import top.infopub.generic.GenericController;
import top.infopub.mgr.common.cnst.Constants;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.hr.domain.StaffOfficeDomain;
import top.infopub.mgr.hr.service.DeptInfoService;
import top.infopub.mgr.hr.service.OrgInfoService;
import top.infopub.mgr.hr.service.WsStaffOfficeService;
import top.infopub.mgr.sys.service.MenuService;
import top.infopub.mgr.sys.service.OperatorService;
import top.infopub.mgr.sys.vo.MenuVo;
import top.infopub.mgr.util.LogUtil;
import top.infopub.mgr.util.StreamRenderUtil;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.tdp.util.BizParaUtil;


/**
 * mgr系统主入口
 * @author Awoke
 * @version 2018年10月15日
 * @see SystemController
 * @since
 */
@Controller
public class SystemController extends GenericController {

    @Autowired
    private OperatorService operatorService;

    @Autowired
    private MenuService menuService;

    @Autowired
    private WsStaffOfficeService wsStaffOfficeService;

    @Autowired
    private OrgInfoService orgInfoService;

    @Autowired
    private DeptInfoService deptInfoService;

    /**
     * 登录页面
     */
    @RequestMapping("/mgr/login")
    public String login(HttpServletRequest request) {
        return "sys/laylogin";
    }

    /**
     * 主页
     */
    @RequestMapping("/mgr/main")
    public String redictMain(ModelMap modelMap, HttpServletRequest request) {
        // 总部公司ID
        SessionUserUtils.setSessionAttribute("superOrgId", BizParaUtil.get("super_org_id"));
        // 获取登录用户信息
        AuthorizationVO authorizationVO = SessionUserUtils.getSessionAttributeForUserDtl();
        modelMap.put("operator", authorizationVO);
        // 获得当前登录用户可见的所有公司与其子孙公司ids 不为空时存入session中
        String visibleOrgIds = wsStaffOfficeService.myAllVisibleOrg();
        if (!StringUtils.isBlank(visibleOrgIds)) {
            SessionUserUtils.setSessionAttribute("visibleOrgIds", visibleOrgIds);
        }
        // 设置默认公司部门到session中
        StaffOfficeDomain dom = wsStaffOfficeService.defaultOrgDept();
        if (null != dom) {
            // session已经存在 则不覆盖
            if (null == SessionUserUtils.getSessionAttribute("bindOrgId")) {
                SessionUserUtils.setSessionAttribute("bindOrgId", dom.getOrgId());
            }
            if (null == SessionUserUtils.getSessionAttribute("bindOrgName")) {
                SessionUserUtils.setSessionAttribute("bindOrgName", dom.getCompName());
            }
            if (null == SessionUserUtils.getSessionAttribute("bindDeptId")) {
                SessionUserUtils.setSessionAttribute("bindDeptId", dom.getDeptId());
            }
            if (null == SessionUserUtils.getSessionAttribute("bindDeptName")) {
                SessionUserUtils.setSessionAttribute("bindDeptName", dom.getDeptName());
            }
            // 输出所有的公司部门
            List<StaffOfficeDomain> myAllOrgDept = wsStaffOfficeService.myAllOrgDept();
            request.setAttribute("myAllOrgDept", myAllOrgDept);
        }
        return "sys/laymain";
    }

    /**
     * 切换当前公司部门
     * @return
     */
    @RequestMapping("/mgr/switchOrgDept")
    @ResponseBody
    @SuppressWarnings("unchecked")
    public RspVo<String> switchOrgDept(String chosenOrgDeptId) {
        String loginUserName = SessionUserUtils.getSessionUserName();
        if (StringUtils.isBlank(loginUserName)) {
            return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo(Constants.BAD_PARAMETERS_REQUEST);
        }
        if (StringUtils.isBlank(chosenOrgDeptId)) {
            return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("未设置公司—部门，无法切换~");
        }
        // ${od.orgId}-${od.deptId}
        String orgId = chosenOrgDeptId.split("-")[0];
        String compName = orgInfoService.selectByPrimaryKey(orgId).getCompName();
        String deptId = chosenOrgDeptId.split("-")[1];
        String deptName = deptInfoService.selectByPrimaryKey(deptId).getDeptName();
        // 更新session中的当前公司部门
        SessionUserUtils.setSessionAttribute("bindOrgId", orgId);
        SessionUserUtils.setSessionAttribute("bindOrgName", compName);
        SessionUserUtils.setSessionAttribute("bindDeptId", deptId);
        SessionUserUtils.setSessionAttribute("bindDeptName", deptName);
        log.debug("{} switchOrgDept in session successfully~", loginUserName);
        return RspVo.getSuccessMsgResponse(compName + "—" + deptName);
    }

    /**
     * 退出登录
     */
    @RequestMapping("/mgr/logout")
    public String logout(HttpServletRequest request) {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            // session 会销毁，在SessionListener监听session销毁，清理权限缓存
            subject.logout();
        }
        return "redirect:/mgr/login";
    }

    /**
     * 跳转到欢迎首页
     */
    @RequestMapping(value = "/mgr/welcome")
    public String toWelcome() {
        return "sys/welcome";
    }

    /**
     * 跳转到系统级告警接收页面
     */
    @RequestMapping(value = "/mgr/warnSetup")
    public String warnSetup() {
        return "sys/lay-warn-receive-setup";
    }

    /**
     * 用户未授权，对应shiro配置中的 unauthorizedUrl
     * @return 
     * @see
     */
    @RequestMapping("/mgr/unauthorized")
    public String unauthorized(HttpServletRequest request, HttpServletResponse response) {
        if ((request.getHeader("x-requested-with") != null && request.getHeader("x-requested-with").equalsIgnoreCase(
            "XMLHttpRequest"))
            || (request.getContentType() != null && request.getContentType().toLowerCase().indexOf(
                "multipart/form-data".toLowerCase()) > -1)
            || (request.getContentType() != null && request.getContentType().toLowerCase().indexOf(
                "application/x-www-form-urlencoded".toLowerCase()) > -1)) {
            RspVo<?> resVo = ErrorCodeEnum.ERROR_COMMON_SYSTEM.getRspVo(Constants.NO_OPERATION_CURRENT);
            StreamRenderUtil.render(resVo, response, null);
            return null;
        }
        else {
            return "error/unauthorized";
        }
    }

    /**
     * 异步获取当前用户的导航菜单
     */
    @RequestMapping(value = "/mgr/navi")
    @ResponseBody
    public List<MenuVo> navi() {
        String loginUserId = SessionUserUtils.getSessionUserId();
        // 未登录 则返回空 
        if (StringUtils.isBlank(loginUserId)) {
            return new LinkedList<>();
        }
        List<MenuVo> list = menuService.queryNaviJsonByUser(loginUserId);
        return list;
    }

    /**
     * 修改密码
     * @param spassword 新密码
     * @param spassword1 确认密码
     * @param id 用户ID
     * @return
     */
    @RequestMapping("/mgr/editPwd")
    @ResponseBody
    @SuppressWarnings("unchecked")
    public RspVo<String> editPwd(String oldpwd, String newpwd, String renewpwd) {
        String loginUserName = SessionUserUtils.getSessionUserName();
        if (StringUtils.isBlank(loginUserName)) {
            return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo(Constants.BAD_PARAMETERS_REQUEST);
        }
        if (!StringUtils.equals(newpwd, renewpwd)) {
            return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo(Constants.CHANGE_PWD_NEWS_NOT_EQUALS);
        }
        if (operatorService.queryByNameAndPw(loginUserName, oldpwd) == 0) {
            return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo(Constants.CHANGE_PWD_OLD_IS_WRONG);
        }
        if (StringUtils.equals(oldpwd, newpwd)) {
            return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo(Constants.CHANGE_PWD_OLD_EQUALS_NEW);
        }
        operatorService.updatePassword(loginUserName, newpwd);
        // 操作日志
        LogUtil.bizLog(LogUtil.LogModelType.SYSTEM, LogUtil.AcctionType.UPDATE, loginUserName
                                                                                + " 修改密码", "");
        return RspVo.getSuccessResponse();
    }

    /**
     * 使用pdfjs预览pdf文档
     * @return
     */
    @RequestMapping(value = "/viewPdf", method = RequestMethod.GET)
    public String viewPdf(HttpServletRequest request, HttpServletResponse response,
                          String streamUrl, String fileName) {
        request.setAttribute("streamUrl", streamUrl);
        try {
            // 用来设置文档title
            request.setAttribute("fileName", URLDecoder.decode(fileName, "UTF-8"));
        }
        catch (UnsupportedEncodingException e) {
            // ignore
        }
        return "pdfjs/viewPdf";
    }

}
